package com.infinit.easyreader.fragment;

import android.app.Activity;
import android.app.Fragment;
import android.content.ClipData;
import android.content.Intent;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.GridView;
import android.widget.LinearLayout;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.RelativeLayout;

import com.infinit.easyreader.Biz.BookBiz;
import com.infinit.easyreader.R;
import com.infinit.easyreader.adpter.BooksAdapter;
import com.infinit.easyreader.entity.Book;
import com.infinit.easyreader.ui.HomeActivity;
import com.infinit.easyreader.ui.MyFilePickerActivity;
import com.infinit.easyreader.ui.ReaderActivity;
import com.infinit.easyreader.utils.FindBookType;
import com.nononsenseapps.filepicker.FilePickerActivity;

import java.util.ArrayList;
import java.util.List;

import butterknife.Bind;
import butterknife.ButterKnife;
import butterknife.OnClick;

/**
 * 类：BooksFragment [V 1.0.0]
 * 包含类 : com.infinit.easyreader.fragment.BooksFragment
 * 作用：书库的Fragment
 * Created by rzy on 2016/1/30.
 */
public class BooksFragment extends android.support.v4.app.Fragment {


    public static final String FILE_PATH = "book_path";
    private static final int FILE_CODE = 1;
    @Bind(R.id.rlAddBook)
    RelativeLayout rlAddBook;
    private GridView gvBooks;
    private List<Book> books;
    private BookBiz bookBiz;
    private Handler handler;
    private BooksAdapter adapter;
    private RadioGroup rgEditBar;
    private LinearLayout llFooter;
    private RadioButton rbEditCollect;

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_books, container, false);
        ButterKnife.bind(this, view);
        gvBooks = (GridView) view.findViewById(R.id.gvBooks);
        getViewOfParent();
        setListener();
        handler = new Handler(new Handler.Callback() {
            @Override
            public boolean handleMessage(Message msg) {
                switch (msg.what) {
                    case BookBiz.FIND_BOOKS_SUCCESS:
                        //noinspection unchecked
                        books = (List<Book>) msg.obj;
                        //将添加书籍按钮设置为GONE
                        rlAddBook.setVisibility(View.GONE);
                        gvBooks.setVisibility(View.VISIBLE);
                        adapter.setDataList(books);
                        adapter.notifyDataSetChanged();
                        break;
                    case BookBiz.FIND_BOOKS_FAIL:
                        gvBooks.setVisibility(View.GONE);
                        rlAddBook.setVisibility(View.VISIBLE);
                        break;
                }
                return true;
            }
        });
        bookBiz = new BookBiz(getActivity(), handler);


        books = new ArrayList<>();
        adapter = new BooksAdapter(books, getActivity());
        gvBooks.setAdapter(adapter);
        bookBiz.new FindBooksTask().execute(FindBookType.ALL);
        return view;
    }


    /**
     * 作用：在再次显示时更新数据
     */
    public void updateData() {
        bookBiz.new FindBooksTask().execute(FindBookType.ALL);
    }


    /**
     * 作用：为添加书籍按钮增加监听事件
     * 参数说明：EXTRA_ALLOW_MULTIPLE 允许多选
     * EXTRA_ALLOW_CREATE_DIR：允许创建目录
     * EXTRA_MODE：选择模式
     * EXTRA_START_PATH：起始路径
     */

    @OnClick({R.id.ibAddBooks, R.id.ibAddBook})
    void addBook() {
        //这里使用第三方的FilePicker https://github.com/spacecowboy/NoNonsense-FilePicker
        Intent intent = new Intent(getActivity(), MyFilePickerActivity.class);
        intent.putExtra(MyFilePickerActivity.EXTRA_ALLOW_MULTIPLE, false);
        intent.putExtra(MyFilePickerActivity.EXTRA_ALLOW_CREATE_DIR, false);
        intent.putExtra(MyFilePickerActivity.EXTRA_MODE, MyFilePickerActivity.MODE_FILE);
        intent.putExtra(MyFilePickerActivity.EXTRA_START_PATH, Environment.getExternalStorageDirectory().getPath());
        startActivityForResult(intent, FILE_CODE);
    }


    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (requestCode == FILE_CODE && resultCode == Activity.RESULT_OK) {
            if (data.getBooleanExtra(MyFilePickerActivity.EXTRA_ALLOW_MULTIPLE, false)) {
                // For JellyBean and above
                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN) {
                    ClipData clip = data.getClipData();

                    if (clip != null) {
                        for (int i = 0; i < clip.getItemCount(); i++) {
                            Uri uri = clip.getItemAt(i).getUri();
                            //添加书籍
                            bookBiz.addBooks(uri.getPath());
                            //更新显示
                            bookBiz.new FindBooksTask().execute(FindBookType.ALL);
                        }
                    }
                    // For Ice Cream Sandwich
                } else {
                    ArrayList<String> paths = data.getStringArrayListExtra
                            (FilePickerActivity.EXTRA_PATHS);

                    if (paths != null) {
                        for (String path : paths) {
                            Uri uri = Uri.parse(path);
                            //添加书籍
                            bookBiz.addBooks(uri.getPath());
                            //更新显示
                            bookBiz.new FindBooksTask().execute(FindBookType.ALL);
                        }
                    }
                }

            } else {
                Uri uri = data.getData();
                //添加书籍
                bookBiz.addBooks(uri.getPath());
                //更新显示
                bookBiz.new FindBooksTask().execute(FindBookType.ALL);
            }
        }
    }

    /**
     * 作用：获得Activity的编辑按钮控件
     */

    private void getViewOfParent() {
        Activity activity = getActivity();
        rgEditBar = (RadioGroup) activity.findViewById(R.id.rgEditBar);
        rbEditCollect = (RadioButton) activity.findViewById(R.id.rbEditCollect);
        llFooter = (LinearLayout) activity.findViewById(R.id.footer);
    }

    /**
     * 作用：为指定的控件设置监听器
     */
    private void setListener() {

        /**
         * 作用：为GridView的子项目设置长按监听器
         * 当长按时，下方的编辑条显示，隐藏TAB栏
         */
        gvBooks.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {
            @Override
            public boolean onItemLongClick(AdapterView<?> parent, View view, int position, long id) {
                //当Book已经为收藏中时,显示取消收藏
                rbEditCollect.setText("收藏");
                if (books.get(position).isFavorite()) {
                    rbEditCollect.setText("取消收藏");
                }
                llFooter.setVisibility(View.GONE);
                rgEditBar.setVisibility(View.VISIBLE);
                HomeActivity activity = (HomeActivity) getActivity();
                activity.setCurrentStatus(books.get(position), bookBiz, FindBookType.ALL);
                return true;
            }
        });

        /**
         * 作用：为GridView的子项目设置点击监听器
         */

        gvBooks.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                Intent intent = new Intent(getActivity(), ReaderActivity.class);
                intent.putExtra(FILE_PATH, books.get(position));
                startActivity(intent);
            }
        });


    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        bookBiz.closeDatabase();
        bookBiz = null;
        ButterKnife.unbind(this);
    }
}

